/*
 * wifi_water_level.c
 *
 * Created: 12/18/2012 8:47:33 PM
 *  Author: Jeramy
 */ 

#include <avr/io.h>
#include <stdio.h>
#include <util/delay.h>
#include <string.h>
#include <avr/interrupt.h>
#include <avr/sfr_defs.h>

#define SAMPLE_NUM 20		/* Max value of 255 */

#define BAUD 9600ul
#define MYUBRR F_CPU/16/BAUD-1
#define nop()  __asm__ __volatile__("nop")

void Sample_Report(uint16_t in);
void PIN_Init(void);
void COMPARATOR_Init(void);
void TIMER1_Init(void);
void USART_Init(unsigned int ubrr);
void USART_Transmit(char *data);

/* Public variables used to sample */
uint16_t sample_values[SAMPLE_NUM];
uint8_t sample_ct;

int main(void)
{
	char msg[15];

	PIN_Init();
	USART_Init(MYUBRR);
	COMPARATOR_Init();
	TIMER1_Init();
	
    while(1)
    {
		/* Reset flags */
		ACSR |= (1<<ACI);
		TIFR1 |= (1<<TOV1);
		
        TCNT1 = 0;					/* Reset Timer */
        PORTC |= (1<<PORTC0);		/* Set the pulse pin high */
		
		/* If either the comparator goes high or the timer overflows proceed */
		while (!(ACSR & (1<<ACI)) && !(TIFR1 & (1<<TOV1)));
		
		PORTC &= ~(1<<PORTC0);		/* Set the pulse pin low */

		if (ACSR & (1<<ACI))		/* If comparator went high */
		{
			Sample_Report(TCNT1);

		}
		else
		{
			sprintf(msg,"Overflow");
			USART_Transmit(msg);

		}
						
		_delay_ms(5);

    }
}

void Sample_Report(uint16_t in)
{
	uint8_t i = 0;
	uint32_t sample_rtn = 0;
	uint16_t int_average = 0;
	float average = 0.0;
	char msg[90];
	
	sample_values[sample_ct++] = in;

	if (sample_ct == SAMPLE_NUM)		/* sample_value[sample_num] is going to be null */
	{
		for (i = 0; i < (SAMPLE_NUM); i++)
		{
			sample_rtn += sample_values[i];
		}

		average = (float)sample_rtn / (float)SAMPLE_NUM;
		int_average = (uint16_t)round(average);
		
		sprintf(msg,"%u", int_average);
		USART_Transmit(msg);
		
		sample_ct = 0;

	}
}

void PIN_Init(void)
{
	DDRC |= (1<<DDC0);		/* Set PC0 as output; this is the pulse pin */
	
}	

void COMPARATOR_Init(void)
{
	ACSR |= (1<<ACIS1)|(1<<ACIS0);		/* Enable comparator flag on rising edge */
	DIDR1 |= (1<<AIN1D)|(1<<AIN0D);		/* Digital Input Disable */
	
}

void TIMER1_Init(void)
{
	TCCR1B |= (1<<CS10);		/* Timer counts a frequency of CPU; clk/1 */
	
}

void USART_Init( unsigned int ubrr)
{
	/*Set baud rate */
	UBRR0H = (unsigned char)(ubrr>>8);
	UBRR0L = (unsigned char)ubrr;
	/* Enable transmitter */
	UCSR0B |= (1<<TXEN0);
	/* Set frame format: 8data, 1stop bit */
	UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
}

void USART_Transmit(char *data)
{
	char str[100];
	char *p_str = &str[0];
	
	strcpy(str, data);
	strcat(str, "\r\n");	/* Carriage Return & Line Feed */
	
	while(*p_str)
	{
		/* Wait for empty transmit buffer */
		while (!(UCSR0A & (1<<UDRE0)));
		/* Put data into buffer, sends the data */
		UDR0 = *p_str++;

	}
}